package de.lulusoft.anothertorrent.gui.views;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.util.HashMap;

import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.part.ViewPart;

import de.lulusoft.anothertorrent.core.AnotherTorrentCore;
import de.lulusoft.anothertorrent.core.servers.Server;
import de.lulusoft.anothertorrent.gui.AnotherTorrentGui;
import de.lulusoft.anothertorrent.gui.commands.AddServerCommand;
import de.lulusoft.anothertorrent.gui.commands.DeleteServerCommand;
import de.lulusoft.anothertorrent.gui.commands.EditServerCommand;
import de.lulusoft.anothertorrent.gui.commands.OpenXmlRpcConsoleCommand;
import de.lulusoft.anothertorrent.gui.views.Providers.ServerViewContentProvider;
import de.lulusoft.anothertorrent.gui.views.Providers.ServerViewLabelProvider;

public class ServerView extends ViewPart implements Serializable{

	private static final long serialVersionUID = 4618334111119106047L;

	public static final String ID = "de.lulusoft.anothertorrent.gui.views.ServerView";
	
	public static final String P_SERVER = "serverChanged";
	public static final String STATE_PROPERTYCHANGESUPPORT = "STATE_PROPERTYCHANGESUPPORT";
	
	private TreeViewer viewer = null;
	private Menu contextMenu = null;
	private MenuItem itemAddServer = null;
	private MenuItem itemEditServer = null;
	private MenuItem itemRemoveServer = null;
	private MenuItem itemOpenConsole = null;
	
	private PropertyChangeSupport propertyChangeSupport = null;
	
	private static ServerView me = null;
	
	public ServerView() {
		me=this;
	}
	
	public static void setInput(Object input)
	{
		if (me != null && me.viewer != null)
		{
			me.viewer.setInput(input);
		}
	}
	
	public IStructuredSelection getViewerSelection()
	{
		return (IStructuredSelection)viewer.getSelection();
	}
	
	@Override
	public void init(IViewSite site, IMemento memento) throws PartInitException {
		super.init(site, memento);
		propertyChangeSupport = new PropertyChangeSupport(this);
	}


	@Override
	public void createPartControl(Composite parent) {
		
		viewer = new TreeViewer(parent, SWT.SINGLE | SWT.NONE);
		viewer.setContentProvider(new ServerViewContentProvider());
		viewer.setLabelProvider(new ServerViewLabelProvider());
		viewer.addDoubleClickListener(new IDoubleClickListener() {
		
			@Override
			public void doubleClick(DoubleClickEvent event) {
				if (event.getSelection() instanceof IStructuredSelection)
				{
					IStructuredSelection sel = (IStructuredSelection)event.getSelection();
					if (sel.getFirstElement() instanceof Server)
					{
						Server srv = (Server)sel.getFirstElement();
						// Open Server
						try 
						{
							OverviewView ov = (OverviewView)
								AnotherTorrentGui.getDefault()
								.getWorkbench().getActiveWorkbenchWindow()
								.getActivePage().showView(OverviewView.ID, 
										srv.getName(), IWorkbenchPage.VIEW_ACTIVATE);
							ov.setInput(srv);
						} catch (PartInitException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}		
					}
				}	
				
			}
		});
		
		viewer.addSelectionChangedListener(new ISelectionChangedListener() {
		
			@Override
			public void selectionChanged(SelectionChangedEvent event) {
				if (event.getSelection() instanceof IStructuredSelection)
				{
					IStructuredSelection sel = (IStructuredSelection)event.getSelection();
					if (sel.getFirstElement() instanceof Server)
					{
						itemRemoveServer.setEnabled(true);
						itemOpenConsole.setEnabled(true);
						itemEditServer.setEnabled(true);
					}
					else
					{
						itemRemoveServer.setEnabled(false);
						itemOpenConsole.setEnabled(false);
						itemEditServer.setEnabled(false);
					}
					propertyChangeSupport.firePropertyChange(P_SERVER, null, sel.getFirstElement());
				}		
			}
		});
		
		contextMenu = new Menu(viewer.getControl().getShell(), SWT.POP_UP);
	    itemAddServer = new MenuItem(contextMenu, SWT.PUSH);
	    itemAddServer.setText("Add Server");
	    itemAddServer.setImage(AnotherTorrentGui.createImage("server_add.png"));
	    itemAddServer.addSelectionListener(new SelectionListener() {
		
			@Override
			public void widgetSelected(SelectionEvent e) {
				ICommandService service = (ICommandService)getSite().getService(ICommandService.class);
				Command cmd = service.getCommand(AddServerCommand.ID);
				ExecutionEvent event = new ExecutionEvent(cmd, new HashMap<String, String>(), null, null);
				try {
					cmd.executeWithChecks(event);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
			}
		});
	    
	    itemEditServer = new MenuItem(contextMenu, SWT.PUSH);
	    itemEditServer.setText("Edit Server");
	    itemEditServer.setImage(AnotherTorrentGui.createImage("server_edit.png"));
	    itemEditServer.setEnabled(false);
	    itemEditServer.addSelectionListener(new SelectionListener() {
		
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (viewer.getSelection() instanceof IStructuredSelection)
				{
					IStructuredSelection sel = (IStructuredSelection)viewer.getSelection();
					if (sel.getFirstElement() instanceof Server)
					{
						ICommandService service = (ICommandService)getSite().getService(ICommandService.class);
						Command cmd = service.getCommand(EditServerCommand.ID);
						ExecutionEvent event = new ExecutionEvent(cmd, new HashMap<String, String>(), null, null);
						try {
							cmd.executeWithChecks(event);
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				}
			}
		
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
			}
		});
	    
	    itemRemoveServer = new MenuItem(contextMenu, SWT.PUSH);
	    itemRemoveServer.setText("Remove Server");
	    itemRemoveServer.setImage(AnotherTorrentGui.createImage("server_delete.png"));
	    itemRemoveServer.setEnabled(false);
	    itemRemoveServer.addSelectionListener(new SelectionListener() {
		
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (viewer.getSelection() instanceof IStructuredSelection)
				{
					IStructuredSelection sel = (IStructuredSelection)viewer.getSelection();
					if (sel.getFirstElement() instanceof Server)
					{
						ICommandService service = (ICommandService)getSite().getService(ICommandService.class);
						Command cmd = service.getCommand(DeleteServerCommand.ID);
						ExecutionEvent event = new ExecutionEvent(cmd, new HashMap<String, String>(), null, null);
						try {
							cmd.executeWithChecks(event);
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				}
			}
		
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
			}
		});
	    
	    itemOpenConsole = new MenuItem(contextMenu, SWT.PUSH);
	    itemOpenConsole.setText("Open XmlRPC Console");
	    itemOpenConsole.setImage(AnotherTorrentGui.createImage("application_xp_terminal.png"));
	    itemOpenConsole.setEnabled(false);
	    itemOpenConsole.addSelectionListener(new SelectionListener() {
		
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (viewer.getSelection() instanceof IStructuredSelection)
				{
					IStructuredSelection sel = (IStructuredSelection)viewer.getSelection();
					if (sel.getFirstElement() instanceof Server)
					{
						ICommandService service = (ICommandService)getSite().getService(ICommandService.class);
						Command cmd = service.getCommand(OpenXmlRpcConsoleCommand.ID);
						ExecutionEvent event = new ExecutionEvent(cmd, new HashMap<String, String>(), null, null);
						try {
							cmd.executeWithChecks(event);
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				}
			}
		
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
			}
		});
	    
	    viewer.getControl().setMenu(contextMenu);
	    
	    viewer.setInput(AnotherTorrentCore.getDefault().getServerManager());

	}

	@Override
	public void setFocus() {
	}
	
	public void addPropertyChangeListener(PropertyChangeListener listener)
	{
		propertyChangeSupport.addPropertyChangeListener(listener);
	}

	public void removePropertyChangeListener(PropertyChangeListener listener)
	{
		propertyChangeSupport.removePropertyChangeListener(listener);
	}
}
